package com.wt.chat.controller;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.request.LoginRequest;
import com.wt.chat.response.ResponseResult;
import com.wt.chat.service.LoginService;
import com.wt.chat.utils.CookieUtils;
import com.wt.chat.utils.Keys;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @description
 * @author: wangtao
 * @date:14:59 2019/11/8
 * @email:taow02@jumei.com
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisCache redisCache;

    @RequestMapping("/doLogin")
    public ResponseResult doLogin(HttpServletResponse response, @RequestBody LoginRequest loginRequest) {
        if (StringUtils.isEmpty(loginRequest.getUsername()) || StringUtils.isEmpty(loginRequest.getToken())) {
            return new ResponseResult().code(ResponseResult.CodeType.ERROR.getValue()).msg("用户名密码不能为空");
        }
		loginService.doLogin(loginRequest);
        String token = UUID.randomUUID().toString().replace("-", "");
        redisCache.set(token, 1, 24 * 60 * 60);
        CookieUtils.addCookie(response, Keys.LOGIN_COOKIE_KEY, token, -1);
        return new ResponseResult().code(ResponseResult.CodeType.OK.getValue());
    }

    /**
     * 获取随机数，5位
     */
    @RequestMapping("/generateNonceStr")
    public ResponseResult getNonceStr() {
        String nonceStr = loginService.generateNonceStr();
        return new ResponseResult().code(StringUtils.isEmpty(nonceStr) ? 1 : 0).body(nonceStr);
    }

}
